package com.gzist.elderlyserviceplatform.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gzist.elderlyserviceplatform.entity.dto.InfoNewsQueryByCategoryDTO;
import com.gzist.elderlyserviceplatform.entity.dto.InfoNewsUpdateDTO;
import com.gzist.elderlyserviceplatform.entity.dto.InfoNewsPageDTO;
import com.gzist.elderlyserviceplatform.entity.po.InfoNews;
import com.gzist.elderlyserviceplatform.entity.vo.InfoNewsQueryByCategoryVO;
import com.gzist.elderlyserviceplatform.entity.vo.InfoNewsQueryByLatestOrHotVO;
import com.gzist.elderlyserviceplatform.entity.vo.InfoNewsVo;
import com.gzist.elderlyserviceplatform.mapper.InfoNewsMapper;
import com.gzist.elderlyserviceplatform.service.CommentService;
import com.gzist.elderlyserviceplatform.service.InfoNewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gzist.elderlyserviceplatform.service.RedisService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 资讯信息表 服务实现类
 */
@Service
@RequiredArgsConstructor
public class InfoNewsServiceImpl extends ServiceImpl<InfoNewsMapper, InfoNews> implements InfoNewsService {

    private final InfoNewsMapper infoNewsMapper;
    private final CommentService commentService;
    private final RedisService redisService;
    /**
     * 资讯根据分类id将其归为未分类
     *
     * @param categoryId
     */
    public void c_delete(String categoryId) {
        LambdaUpdateWrapper<InfoNews> wrapper = new UpdateWrapper<InfoNews>().lambda();
        if (StrUtil.isNotBlank(categoryId)) {
            wrapper.eq(InfoNews::getCategoryId, categoryId)
                    .set(InfoNews::getCategoryId, 1);
        }
        this.update(wrapper);

    }

    @Override
    public Page<InfoNewsVo> queryPage(InfoNewsPageDTO infoNewsPageDTO) {
        Page<InfoNewsVo> page = new Page<>(infoNewsPageDTO.getPageNum(), infoNewsPageDTO.getPageSize());
        return infoNewsMapper.queryPage(page, infoNewsPageDTO);
    }

    @Override
    public List<InfoNewsQueryByLatestOrHotVO> listByLatestOrHot(String id) {
        ArrayList<InfoNewsQueryByLatestOrHotVO> finalList = new ArrayList<>();
        // 当id=1时，查询最新资讯，当id=2时，查询最热资讯，均是查询前4条即可
        LambdaQueryWrapper<InfoNews> wrapper = Wrappers.lambdaQuery();
        if ("1".equals(id)) {
            wrapper.eq(InfoNews::getDelFlag, 0)
                    .orderByDesc(InfoNews::getCreateTime)
                    .last("limit 4");
        } else if ("2".equals(id)) {
            wrapper.eq(InfoNews::getDelFlag, 0)
                    .orderByDesc(InfoNews::getViewCount)
                    .last("limit 4");
        } else {
            // 返回一个空集合
            return Collections.emptyList();
        }
        List<InfoNews> queryList = this.list(wrapper);
        // 遍历集合，将数据封装到InfoNewsQueryByLatestOrHotVO对象中，并添加到finalList集合中进行返回
        queryList.forEach(item -> {
            InfoNewsQueryByLatestOrHotVO infoNewsQueryByLatestOrHotVO = new InfoNewsQueryByLatestOrHotVO();
            infoNewsQueryByLatestOrHotVO.setId(item.getId());
            infoNewsQueryByLatestOrHotVO.setTitle(item.getTitle());
            infoNewsQueryByLatestOrHotVO.setTime(DateUtil.format(item.getPublishTime(), "yyyy-MM-dd HH:mm"));
            finalList.add(infoNewsQueryByLatestOrHotVO);
        });
        return finalList;
    }

    /**
     * 根据类别查询信息新闻的分页数据
     *
     * @param dto 查询参数，包括分类id、页码和页面大小
     * @return 返回一个分页对象，包含按分类id查询的新闻列表
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Page<InfoNewsQueryByCategoryVO> queryPageByCategory(InfoNewsQueryByCategoryDTO dto) {
        Page<InfoNews> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        LambdaQueryWrapper<InfoNews> wrapper = Wrappers.lambdaQuery();
        if (StrUtil.isNotBlank(dto.getCategoryId())) {
            wrapper.eq(InfoNews::getCategoryId, dto.getCategoryId());
        }
        wrapper.eq(InfoNews::getDelFlag, 0)
                .orderByDesc(InfoNews::getUpdateTime);
        Page<InfoNews> pageResult = this.page(page, wrapper);
        List<InfoNewsQueryByCategoryVO> collect = pageResult.getRecords().stream().map(item -> {
            InfoNewsQueryByCategoryVO infoNews = new InfoNewsQueryByCategoryVO();
            infoNews.setId(item.getId());
            infoNews.setTitle(item.getTitle());
            infoNews.setTime(DateUtil.format(item.getCreateTime(), "yyyy-MM-dd HH:mm"));
            infoNews.setSummary(item.getSummary());
            infoNews.setViewCount(String.valueOf(item.getViewCount()));
            // 获取评论数
            infoNews.setComments(String.valueOf(commentService.getCommentsByRootId(item.getId())));
            infoNews.setCover(item.getCover());
            return infoNews;
        }).collect(Collectors.toList());
        // 将查询到的结果封装到Page对象中并返回
        Page<InfoNewsQueryByCategoryVO> pageResultVO = new Page<>();
        BeanUtil.copyProperties(pageResult, pageResultVO);
        pageResultVO.setRecords(collect);

        return pageResultVO;
    }


    /**
     * 资讯信息修改
     *
     * @param infoNewsUpdateDTO 包括资讯id、简介、图片地址、分类类别
     */
    @Override
    public boolean update(InfoNewsUpdateDTO infoNewsUpdateDTO) {
        LambdaUpdateWrapper<InfoNews> wrapper = new UpdateWrapper<InfoNews>().lambda();
        wrapper.eq(InfoNews::getId, infoNewsUpdateDTO.getId());

        InfoNews infoNews = new InfoNews();
        //拷贝属性到infoNews对象
        BeanUtil.copyProperties(infoNewsUpdateDTO, infoNews);
        return this.update(infoNews, wrapper);

    }

    /**
     * 获取资讯详情
     * @param newsId 资讯 ID
     * @return 资讯详情
     */
    public InfoNews getNewsDetail(String newsId) {
        InfoNews infoNews = infoNewsMapper.selectById(newsId);
        if (infoNews == null) {
            throw new RuntimeException("资讯不存在");
        }
        // 从 Redis 获取浏览量
        Integer viewCountFromRedis = redisService.getViewCount(newsId);
        if (viewCountFromRedis != null) {
            infoNews.setViewCount(viewCountFromRedis);
        }
        // 增加浏览量
        redisService.incrementViewCount(newsId);
        return infoNews;
    }

}
